import { useRef, useEffect } from 'react';
import { Animated } from 'react-native';
import {
  NavigationScreenProp,
  NavigationRoute,
  NavigationParams,
  NavigationEventSubscription
} from 'react-navigation';

export function useAnimate(configure: any): any {
  const useAnimatedValue = (initialValue: any): any => {
    const ref = useRef(new Animated.Value(initialValue));
    return ref.current;
  };

  const animatedValue = useAnimatedValue(configure.initialValue);

  useEffect(() => {
    configure.animate.apply(useAnimate, arguments);
  });

  return [animatedValue];
}

interface InitRenderProp {
  request?: () => void; // 请求函数
  action?: () => void; // 普通函数逻辑
  willFocus?: () => void; // 监听函数（返回该页面时会调用，例如重新刷新数据）
  didFocus?: () => void; // 监听函数（返回该页面时会调用，例如重新刷新数据）
  returnAction?: () => void; // useEffect return时执行的操作
  dependencies: any[]; // 依赖项
  navigation?: NavigationScreenProp<
    // 用于添加监听
    NavigationRoute<NavigationParams>,
    NavigationParams
  >;
}

export const useInitRender = (props: InitRenderProp): void => {
  const {
    request,
    action,
    willFocus,
    didFocus,
    returnAction,
    dependencies,
    navigation
  } = props;

  useEffect((): void | (() => void) => {
    if (request) {
      setTimeout((): void => {
        request();
      }, 300);
    }

    if (action) {
      action();
    }
    let willFocusSubscription: NavigationEventSubscription | null = null;
    let didFocusSubscription: NavigationEventSubscription | null = null;

    if (willFocus && navigation) {
      willFocusSubscription = navigation.addListener('willFocus', willFocus);
    }

    if (didFocus && navigation) {
      didFocusSubscription = navigation.addListener('didFocus', didFocus);
    }

    return (): void => {
      if (willFocusSubscription) {
        willFocusSubscription.remove();
      }
      if (didFocusSubscription) {
        didFocusSubscription.remove();
      }
      if (returnAction) {
        returnAction();
      }
    };
  }, dependencies);
};
